package com.wx.leetcode;

import java.util.*;

/**
 * @desc: 给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有满足条件且不重复的三元组。
 * <p>
 * 给定数组 nums = [-1, 0, 1, 2, -1, -4]，
 * <p>
 * 满足要求的三元组集合为：
 * [
 * [-1, 0, 1],
 * [-1, -1, 2]
 * ]
 * @author: wx
 * @time: 2020/4/10 1:56 PM
 */
public class ThreeSumTopic {

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList();
        if (nums == null) {
            return ans;
        }

        int n = nums.length;

        if (n < 3) {
            return ans;
        }

        Arrays.sort(nums);
        for (int i = 0; i < n; i++) {

            //去重i
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            //左边下标
            int leftIndex = i + 1;
            //右边下标
            int rightIndex = n - 1;

            while (leftIndex < rightIndex) {
                //比较值是否==0，因为是排好序的，所以判断num，如果num<0向 leftIndex++加大数值，如果num<0 rightIndex--减少数值
                int num = nums[i] + nums[leftIndex] + nums[rightIndex];
                if (num == 0) {
                    ans.add(Arrays.asList(nums[i], nums[leftIndex], nums[rightIndex]));
                    //通过移动下标去重
                    while (leftIndex < rightIndex && nums[leftIndex] == nums[leftIndex + 1]){
                        leftIndex++;
                    }
                    //通过移动下标去重
                    while (leftIndex < rightIndex  && nums[rightIndex] == nums[rightIndex - 1]) {
                        rightIndex--;
                    }
                    leftIndex++;
                    rightIndex--;
                } else if (num < 0){
                    leftIndex++;
                } else if (num > 0){
                    rightIndex--;
                }
            }

        }
        return ans;
    }


    public static void main(String args[]) {
        //-2 -1 0 1 2 3
        int[] nums = new int[]{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6};
        System.out.println(threeSum(nums).toString());
    }


}
